#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /* 关闭蒙版 */
    ui->widget_mask->setGeometry(this->width(),this->height(),0,0);

    /* 创建网络 */
    gn = new Gobang_Network();

    MainWindow::setWindowFlags(Qt::FramelessWindowHint);//隐藏边框
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground, true);

    //m_nBorder表示鼠标位于边框缩放范围的宽度，可以设置为5
    m_nBorderWidth=5;

    ui->pushButton_home->setLayout(ui->horizontalLayout_home);
    ui->pushButton_set->setLayout(ui->horizontalLayout_set);
    ui->pushButton_about->setLayout(ui->horizontalLayout_about);

    h = new home(this->gn);
    s = new set(this->gn);
    a =  new about(this->gn);

    page_index[0] = ui->stackedWidget->addWidget(h);
    page_index[1] = ui->stackedWidget->addWidget(s);
    page_index[2] = ui->stackedWidget->addWidget(a);

    ui->stackedWidget->setCurrentIndex(page_index[0]);

    /* 绑定网络必要槽函数 */
    this->bind_tcp();

    /* 连接主机 */
    gn->t->linkSever();
}

/* 绑定槽函数 */
void MainWindow::bind_tcp() {

    //退到主窗口
    connect(h,&home::on_create_room, this,&MainWindow::on_create_room);

    /* join room succeed */
    connect(gn->t, SIGNAL(join_succeed(uint16_t)),
                this, SLOT(join_succeed(uint16_t)));

    /* 服务器给我id */
    connect(gn->t, SIGNAL(get_id(uint16_t)),
                this, SLOT(get_id(uint16_t)));

    /* 告诉我游戏房间创建完成 */
    connect(gn->t,&tcp::creater_succeed, this,&MainWindow::create_succead);
}

/*  id */
void MainWindow::get_id(uint16_t id)
{
    ui->label_user->setText("您的id:"+QString::number(id));
    ui->label_info->setText("已成功连接服务器");
    gn->my_fd = id;

    gn->t->tx_uint8(A_POST_GET_HOUSE, 0);
}

void MainWindow::slotshow()
{
   err("关闭游戏");
   gn->t->tx_uint16(A_EXIT_ROOM_ID, this->gn->my_fd);

   disconnect(gobang,&scan_gobang::signals_close_game, this,&MainWindow::slotshow);
   show();

   delete gobang;

   gobang = nullptr;
}

void MainWindow::update_window()
{
    //设置位置和大小
    ui->horizontalLayoutWidget_4->setGeometry(QRect(0,0,this->width(),40));
    ui->verticalLayoutWidget->setGeometry(QRect(0,40,this->width()*0.3,this->height()-40));
    ui->stackedWidget->setGeometry(this->width()*0.3,40,this->width()*0.7-10,this->height()-40-10);

    h->setSize(0,0,this->width()*0.7,this->height()-40, QRect(this->x(), this->y(), this->width(), this->height()));
    s->setSize(0,0,this->width()*0.7,this->height()-40);
    a->setSize(0,0,this->width()*0.7,this->height()-40);

    //设置每个切换界面按键样式
    ui->label_home_img->setGeometry(ui->pushButton_home->x(),12,36,36);
    ui->label_set_img->setGeometry(ui->pushButton_set->x(),12,36,36);
    ui->label_about_img->setGeometry(ui->pushButton_about->x(),12,36,36);

    ui->label_home_text->setGeometry(ui->pushButton_home->x()+60,10,40,40);
    ui->label_set_text->setGeometry(ui->pushButton_set->x()+60,10,40,40);
    ui->label_about_text->setGeometry(ui->pushButton_about->x()+60,12,40,40);
}


void MainWindow::create_gobang()
{
    if ( gobang == nullptr) {

        /* 创建棋盘 */
        gobang = new scan_gobang(gn);

        //退到主窗口
        connect(gobang,&scan_gobang::signals_close_game, this,&MainWindow::slotshow);
    }
}

void MainWindow::join_succeed(uint16_t tell_id)
{
    gn->tell_fd = tell_id;
    gn->link_state = 1;

    create_gobang();

    this->gobang->join_room();

    this->gobang->my_printf("系统消息", "用户:"+QString::number(tell_id)+"加入房间");
    this->gobang->setgamemode(PVP);

    this->hide();
}

void MainWindow::paintEvent(QPaintEvent *)
{
    this->update_window();
}

MainWindow::~MainWindow()
{
    log("调用主函数析构");
}

void MainWindow::create_succead()
{
    disconnect(gn->t,&tcp::creater_succeed, this,&MainWindow::create_succead);

    this->hide();

    create_gobang();

    this->gobang->my_printf("系统消息", this->ui->label_user->text() + "房间创建成功");

    this->gobang->create_room();

    delete h->lm;
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        whereismouse=event->pos();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        if(MainWindow::isMaximized() || MainWindow::isMinimized())
        {
            return;
        }
        else
        {
            if (ui->horizontalLayoutWidget_4->underMouse()) {
                MainWindow::move(MainWindow::mapToGlobal(event->pos()-whereismouse));
            }
        }
    }
    event->accept();
}

void MainWindow::on_toolButton_exit_clicked()
{
    err("closeEvent");
    gn->t->tx_uint8(A_EXIT_SERVER_ID,0);
    gn->requestInterruption();
    //delete gn;
    QThread::msleep(110);
    delete this;
}

void MainWindow::on_toolButton_min_clicked()
{
    QWidget::showMinimized();
}

void MainWindow::on_toolButton_magnify_clicked()
{
    if (MainWindow::isMaximized()) {
        MainWindow::showNormal();//还原事件
        ui->toolButton_magnify->setIcon(QIcon(QPixmap(":/images/ma_max.png")));
    } else {
        MainWindow::showMaximized();//最大化事件
        ui->toolButton_magnify->setIcon(QIcon(QPixmap(":/images/ma_min.png")));
    }
}

//nativeEvent主要用于进程间通信-消息传递，使用这种方式后来实现窗体的缩放 [加上了这函数，窗口也能移动了]
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    Q_UNUSED(eventType)
    MSG *param = static_cast<MSG *>(message);

    switch (param->message)
    {
        case WM_NCHITTEST:
        {
            //计算鼠标相对于窗口左上角的坐标。
            int nX = GET_X_LPARAM(param->lParam) - this->geometry().x();
            int nY = GET_Y_LPARAM(param->lParam) - this->geometry().y();

            /*if (childAt(nX, nY) != nullptr)
                return QWidget::nativeEvent(eventType, message, result);*/

            //检查鼠标是否在窗口的边框内部区域，如果在内部区域，
            if (nX > m_nBorderWidth && nX < this->width() - m_nBorderWidth &&
            nY > m_nBorderWidth && nY < this->height() - m_nBorderWidth)
            {
                //qDebug() << "in the title ";
                //检查鼠标位置是否在子控件上，如果是，则调用QWidget的nativeEvent函数进行处理。
                if (childAt(nX, nY) != nullptr)
                    return QWidget::nativeEvent(eventType, message, result);
            }



            // 鼠标区域位于窗体边框，进行缩放
            if ((nX > 0) && (nX < m_nBorderWidth))
                *result = HTLEFT;

            if ((nX > this->width() - m_nBorderWidth) && (nX < this->width()))
                *result = HTRIGHT;

            if ((nY > 0) && (nY < m_nBorderWidth))
                *result = HTTOP;

            if ((nY > this->height() - m_nBorderWidth) && (nY < this->height()))
                *result = HTBOTTOM;

            if ((nX > 0) && (nX < m_nBorderWidth) && (nY > 0)
                    && (nY < m_nBorderWidth))
                *result = HTTOPLEFT;

            if ((nX > this->width() - m_nBorderWidth) && (nX < this->width())
                    && (nY > 0) && (nY < m_nBorderWidth))
                *result = HTTOPRIGHT;

            if ((nX > 0) && (nX < m_nBorderWidth)
                    && (nY > this->height() - m_nBorderWidth) && (nY < this->height()))
                *result = HTBOTTOMLEFT;

            if ((nX > this->width() - m_nBorderWidth) && (nX < this->width())
                    && (nY > this->height() - m_nBorderWidth) && (nY < this->height()))
                *result = HTBOTTOMRIGHT;

            return true;
        }
    }

    return QWidget::nativeEvent(eventType, message, result);
}

void MainWindow::on_pushButton_home_clicked()
{
    mode_setStyle(0);
    ui->stackedWidget->setCurrentIndex(page_index[0]);
}

void MainWindow::on_pushButton_set_clicked()
{
    mode_setStyle(1);
    ui->stackedWidget->setCurrentIndex(page_index[1]);
}

void MainWindow::on_pushButton_about_clicked()
{
    mode_setStyle(2);
    ui->stackedWidget->setCurrentIndex(page_index[2]);
}

void MainWindow::on_create_room()
{
    ui->widget_mask->setGeometry(0,0,this->width(),this->height());
    create_room *cr = new create_room();
    cr->move((this->x()+this->width()/2)-(cr->width()/2), (this->y()+this->height()/2)-(cr->height()/2));

    if( cr->exec() ) {
        h->room_text = cr->getStr();
        qDebug()<<h->room_text;
    } else {
        h->room_text = "";
    }

    log("结束");
    delete cr;

    ui->widget_mask->setGeometry(this->width(),this->height(),0,0);
}

void MainWindow::mode_setStyle(int mode)
{
    QString down(" QPushButton{ \
                 background-color:#ffffff;	 \
                 border-radius:5px;	 \
                 border-color: #A5D6A7; \
                 border-style: solid; \
                 border-width: 2px; \
                 color:back; \
                 padding: 5px; \
             } ");

     QString loose("QPushButton{ \
                  border-style: outset; \
                  font: bold 14px; \
                  min-width:2em; \
                  font-family:华文新魏; \
                  padding: 5px; \
              } \
              QPushButton:hover{ \
                  background-color:#ffffff;	 \
                  border-radius:5px;	 \
                  border-color: #A5D6A7; \
                  border-style: solid; \
                  border-width: 2px; \
                  color:back; \
                  padding: 5px; \
              } \
               \
              QPushButton::pressed,QPushButton::checked{ \
                  background-color:#A5D6A7; \
                  color:white; \
              }");

              ui->pushButton_home->clearMask();
              ui->pushButton_set->clearMask();
              ui->pushButton_about->clearMask();

              ui->pushButton_home->setStyleSheet(loose);
              ui->pushButton_set->setStyleSheet(loose);
              ui->pushButton_about->setStyleSheet(loose);

              if (mode == 0) {
                ui->pushButton_home->setStyleSheet(down);
                ui->label_home_img->setStyleSheet("image: url(:/images/home_on.png);");
              } else {
                ui->label_home_img->setStyleSheet("image: url(:/images/hoem.png);");
              }

              if (mode == 1) {
                ui->pushButton_set->setStyleSheet(down);
                ui->label_set_img->setStyleSheet("image: url(:/images/ste_on.png);");
              } else {
                ui->label_set_img->setStyleSheet("image: url(:/images/set.png);");
              }

              if (mode == 2) {
                ui->pushButton_about->setStyleSheet(down);
                ui->label_about_img->setStyleSheet("image: url(:/images/about_on.png);");
              } else {
                ui->label_about_img->setStyleSheet("image: url(:/images/about.png);");
              }
}

void MainWindow::on_Aimode_clicked()
{
    this->hide();
    this->create_gobang();
    gobang->aigameinit();
}
